const app = getApp();
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    title: {
      type: String,
      value: "选择地址"
    },
    height: {
      type: String,
      value: '300px'
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    selectAddress: ["请选择"],
    currentTab: 0,
    address: [],
    popupShow: false,
    lastChooseId: [],
  },


  /**
   * 组件的方法列表
   */
  methods: {

    init() {
      this.setData({
        selectAddress: ["请选择"],
        currentTab: 0,
        address: [],
        lastChooseId: [],
      })
    },

    move() {},
    hidePopup() {
      this.setData({
        popupShow: false
      })
    },
    selection(ids = []) {
      this.setData({
        popupShow: true
      })
      if (ids.length == 0) {
        this.getProvinces().then(res => {
          this.setData({
            [`address[0].list`]: res,
            [`address[0].time`]: new Date().getTime()
          })
        })
      } else if (ids.length == 3 && ids.toString() != this.data.lastChooseId.toString()) {
        Promise.all([this.getProvinces(), this.getCitys(ids[0]), this.getAreas(ids[1])]).then(([provinces, citys, areas]) => {
          let pIndex = provinces.findIndex(current => current.id == ids[0]);
          let cIndex = citys.findIndex(current => current.id == ids[1]);
          let aIndex = areas.findIndex(current => current.id == ids[2]);
          let selectAddress = [provinces[pIndex].name, citys[cIndex].name, areas[aIndex].name]; //tab的内容
          let time = new Date().getTime();
          let address = [{ //省
              list: provinces,
              scrollViewId: `sid_${pIndex}`,
              index: pIndex,
              time: time + 2,
              id: ids[0]
            },
            { //市
              list: citys,
              scrollViewId: `sid_${cIndex}`,
              index: cIndex,
              time: time + 3,
              id: ids[1]
            },
            { //区县
              list: areas,
              scrollViewId: `sid_${aIndex}`,
              index: aIndex,
              time: time + 4,
              id: ids[2]
            }
          ]
          this.setData({
            selectAddress,
            address,
            scrollViewId: `id_2`, //上面的tab滚动到最后一个
            currentTab: 2, //选中最后一个
          })
        }).catch(e => {
          app.showToast(e)
        });
      }
    },

    deal(subitem, subindex, res, index, address, selectAddress) {

      if (address[index].index != undefined && (index == 0 || index == 1)) {
        for (let i = index; i < address.length; i++) {
          address.pop();
          selectAddress.pop();
        }
      }
      selectAddress[index] = subitem.name;
      selectAddress[index + 1] = "请选择";
      address[index].scrollViewId = `sid_${subindex}`;
      address[index].index = subindex;
      address[index].id = subitem.id;
      address.push({
        list: res,
        scrollViewId: 'sid_0',
        time: new Date().getTime(),
      });
      this.setData({
        currentTab: index + 1,
        scrollViewId: `id_${index+1}`,
        selectAddress,
        address
      })
    },

    choose: function (e) {
      const {
        subitem,
        subindex
      } = e.currentTarget.dataset;
      let index = this.data.currentTab;
      let address = this.data.address;
      let selectAddress = this.data.selectAddress;

      if (index == 0) {
        this.getCitys(subitem.id).then(res => {
          this.deal(subitem, subindex, res, index, address, selectAddress);
        }).catch(e => {
          app.showToast(e)
        })
      } else if (index == 1) {
        this.getAreas(subitem.id).then(res => {
          this.deal(subitem, subindex, res, index, address, selectAddress);
        }).catch(e => {
          app.showToast(e)
        })
      } else if (index == 2) {
        let ids = [];
        address[index].scrollViewId = `sid_${subindex}`;
        address[index].index = subindex;
        address[index].id = subitem.id;
        address.forEach(current => {
          ids.push(current.id);
        })
        selectAddress[index] = subitem.name;
        this.setData({
          currentTab: 2,
          selectAddress,
          lastChooseId: ids,
          address
        })
        this.triggerEvent('complete', {
          ids,
          names: this.data.selectAddress,
        });
        this.hidePopup();
      }

      // let res = [];
      // if (index == 0) {
      //   res = await this.getCitys(subitem.id);
      // } else if (index == 1) {
      //   res = await this.getAreas(subitem.id);
      // }
      // let selectAddress = this.data.selectAddress;
      // if (address[index].index != undefined && (index == 0 || index == 1)) {
      //   for (let i = index; i < address.length; i++) {
      //     address.pop();
      //     selectAddress.pop();
      //   }
      // }
      // if (index < 2) {
      //   selectAddress[index] = subitem.name;
      //   selectAddress[index + 1] = "请选择";
      // } else if (index == 2) {
      //   selectAddress[index] = subitem.name;
      // }
      // address[index].scrollViewId = `sid_${subindex}`;
      // address[index].index = subindex;
      // address[index].id = subitem.id;
      // if (index == 0 || index == 1) {
      //   address.push({
      //     list: res,
      //     scrollViewId: 'sid_0',
      //     time: new Date().getTime(),
      //   });
      // }
      // this.setData({
      //   currentTab: index == 2 ? 2 : index + 1,
      //   scrollViewId: `id_${index+1}`,
      //   selectAddress,
      //   address
      // })

      // if (index == 2) {
      //   const address = this.data.address;
      //   let ids = [];
      //   address.forEach(current => {
      //     ids.push(current.id);
      //   })
      //   this.setData({
      //     lastChooseId: ids
      //   })
      //   this.triggerEvent('complete', {
      //     ids,
      //     names: this.data.selectAddress,
      //   });
      //   this.hidePopup();
      // }
    },

    swichNav(e) {
      const currentTab = this.data.currentTab;
      let cur = e.currentTarget.dataset.current;
      if (currentTab != cur) {
        this.setData({
          currentTab: cur
        })
      }
    },

    switchTab(e) {
      this.setData({
        currentTab: e.detail.current
      })
    },

    //获取区县
    getAreas(cityId) {
      return new Promise((resolve, reject) => {
        app.ajax({
          url: "Common/Common/getArea",
          data: {
            id: cityId
          },
          success: res => {
            if (res.data.code == 1000) {
              resolve(res.data.data)
            } else {
              reject(res.data.message || '获取县失败')
            }
          },
          error: e => {
            reject("网络错误")
          }
        })
      });
    },

    //获取市
    getCitys(provinceId) {
      return new Promise((resolve, reject) => {
        app.ajax({
          url: "Common/Common/getCity",
          data: {
            id: provinceId
          },
          success: res => {
            if (res.data.code == 1000) {
              resolve(res.data.data)
            } else {
              reject(res.data.message || '获取市失败')
            }
          },
          error: e => {
            reject("网络错误")
          }
        })
      });
    },

    //获取省
    getProvinces() {
      return new Promise((resolve, reject) => {
        app.ajax({
          url: "Common/Common/getProvince",
          success: res => {
            if (res.data.code == 1000) {
              resolve(res.data.data)
            } else {
              reject(res.data.message || '获取省失败')
            }
          },
          error: e => {
            reject("网络错误")
          }
        })
      });
    },
  }
})